//
//  YAYISkillSelectViewController.m
//  YAYIDoctor
//
//  Created by Veer on 16/5/13.
//
//

#import "YAYISkillSelectViewController.h"

#import "YAYISkillTool.h"
#import "YAYISkillCell.h"
#import "YAYISkillModel.h"

@interface YAYISkillSelectViewController ()

@property (nonatomic, strong) NSMutableArray *skillArray;

@property (nonatomic, strong) NSArray *sectionArray;//row arr
@property (nonatomic, strong) NSArray *sectionTitleArray;//section arr

@end

@implementation YAYISkillSelectViewController


- (NSMutableArray *)skillArray
{
    if (nil == _skillArray) {
        _skillArray = [NSMutableArray array];
        
//        NSArray *testSkillArray = @[@"超声波洁齿美白", @"瓷贴面修复", @"多颗牙种植", @"单颗牙种植", @"多生牙", @"覆盖义齿", @"非龋齿", @"复杂智齿"];
//        for (NSString *skillName in testSkillArray) {
//            YAYISkillModel *model = [[YAYISkillModel alloc] init];
//            model.name = skillName;
//            [_skillArray addObject:model];
//        }
//        
//        
//        // 将数组分组
//        _sectionArray = [YAYISkillTool getFriendListDataBy:self.skillArray];
//        // 获取组名
//        _sectionTitleArray = [YAYISkillTool getFriendListSectionBy:[_sectionArray mutableCopy]];
//        
//        
//        [self.tableView reloadData];
    }
    return _skillArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    self.title = @"擅长项目";
    
//    self.tableView.sectionIndexBackgroundColor = [UIColor colorWithWhite:0.965 alpha:1];
//    self.tableView.sectionIndexColor = [UIColor darkGrayColor];
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 20, 0);
    self.tableView.showsVerticalScrollIndicator = NO;
    
    [self setupNav];
    [self skillArray];
    [self getDiseaseList];
}


- (void)setupNav
{
    NSString *rightBtnTitleStr = @"保存";
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [button setImage:[UIImage imageNamed:@"back_button"] forState:UIControlStateNormal];
    [button setTitle:rightBtnTitleStr forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    
    button.frame = (CGRect){{0, 0}, CGSizeMake(70, 30)};
    
    // 让按钮内部的所有内容左对齐
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [button addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 修改导航栏左边的item
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}


#pragma mark 点击事件
- (void)saveAction:(UIButton *)sender
{
    YAYILog(@"点击了保存");
    NSMutableString *skillNames = [NSMutableString string];
    
    NSMutableArray *selectedArray = [NSMutableArray array];
    NSMutableArray *notSelectedArray = [NSMutableArray array];
    
    for (NSArray *array in self.sectionArray) {
        for (YAYISkillModel *model in array) {
            if (model.isSelected) {
//                model.isSelected = NO;
                [selectedArray addObject:model];
            }else{
                [notSelectedArray addObject:model];
            }
        }
    }
    
    NSMutableArray *skillNameArray = [NSMutableArray array];
    for (int i = 0; i < selectedArray.count; i++) {
        YAYISkillModel *model = selectedArray[i];
        
//        [skillNameArray addObject:model.name];
        [skillNameArray addObject:model];
        [skillNames appendFormat:@"%@", [NSString stringWithFormat:@"%ld", model.diseaseid]];
        if (i != selectedArray.count - 1) {
            [skillNames appendString:@","];
        }
    }
    
    
//    skillNames = [@"单颗及多颗牙缺失种植修复, 前牙美学种植修复, 复杂阻生智齿拔除, 牙痛, 纠正, 补牙, 洗牙,拔牙,种牙,修复, 非龋齿" mutableCopy];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = self.doctorID;
    if (skillNames.length > 0) {
//        skillNames = @" ";
    }
    param[@"diseaseids"] = skillNames;
    
    YAYILog(@"param:%@", param);

    
    [YAYINetWorking postJsonSerilizeWithURL:me_editSkill param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
        if (error == nil) {
            YAYILog(@"保存标签：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                [SVProgressHUD showWithStatus:@"保存失败"];
                
            }else{
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    // 执行代理刷新上级控制器
                    if ([self.delegate respondsToSelector:@selector(skillSelectSaved:)]) {
                        [self.delegate skillSelectSaved:skillNameArray];
                    }
                    
                });
            }
        }else{
            NSString *message = responseError[@"message"];
             [SVProgressHUD showErrorWithStatus:message];
        }
    }];
}


#pragma mark - 获取数据
- (void)getDiseaseList
{
    [SVProgressHUD show];
    [YAYINetWorking getWithURL:me_diseaseList param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                return;
            }
            
            // 已经选择的项目勾选， 为节省效率这里把已选择的数组转成字典
            NSMutableDictionary *selectedIDDict = [NSMutableDictionary dictionary];
            for (int i = 0; i < self.selectedItemArray.count; i++) {
                
                YAYISkillModel *selectedModel = self.selectedItemArray[i];
                selectedIDDict[@(selectedModel.diseaseid)] = selectedModel.name;
            }
            
            YAYILog(@"selectedIDDict:%@", selectedIDDict);
            
            NSArray *dictArray = dict[@"data"];
            for (NSDictionary *dict in dictArray) {
                YAYISkillModel *model = [[YAYISkillModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                
                if (selectedIDDict[@(model.diseaseid)]) {
                    model.isSelected = YES;
                }
                [self.skillArray addObject:model];
            }

            // 将数组分组
            _sectionArray = [YAYISkillTool getFriendListDataBy:self.skillArray];
            // 获取组名
            _sectionTitleArray = [YAYISkillTool getFriendListSectionBy:[_sectionArray mutableCopy]];
            
            
            [self.tableView reloadData];
        }else{
            
            
        }
        
        // 取消显示hud
        [SVProgressHUD dismiss];
    }];
}


#pragma mark - 代理方法
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 22.0;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //viewforHeader
    id label = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
    if (!label)
    {
        label = [[UILabel alloc] init];
        [label setFont:[UIFont systemFontOfSize:14.5f]];
        
        [label setTextColor:[UIColor grayColor]];
        [label setBackgroundColor:[UIColor colorWithWhite:0.965 alpha:1]];
    }
    
    [label setText:[NSString stringWithFormat:@"  %@",self.sectionTitleArray[section + 1]]];
    
    return label;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _sectionArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [self.sectionArray[section]  count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 50.0;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YAYISkillCell *cell = [YAYISkillCell cellWith:tableView];
    
    
    YAYISkillModel *model = self.sectionArray[indexPath.section][indexPath.row];
    cell.model = model;
    
    // 判断使用什么线
    if (indexPath.row == 0) {
        cell.lineType = LineTypeTopAndBottom;
    }else{
        cell.lineType = LineTypeBottom;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    YAYISkillModel *model = self.sectionArray[indexPath.section][indexPath.row];
    model.isSelected = !model.isSelected;
    
    YAYISkillCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.isSelected = model.isSelected;
    
//    if (model.isSelected) {
//        self.selectedCount++;
//    }else{
//        self.selectedCount--;
//    }
    
}

@end
